package cn.fansunion.photo;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.ListUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONArray;

@Controller
@RequestMapping("")
public class IndexController extends BaseController {

	@Resource
	private PhotoDao photoDao;

	private Logger logger = Logger.getLogger(getClass());

	public String index() {
		return "managePhoto";
	}

	//简化处理,bizid-projectId都为1，不想更改之前的代码
	@RequestMapping("viewPhoto")
	public String viewPhoto(HttpServletResponse response, Model model, Long id) {
		id = 1L;
		PhotoVo photoVo = viewPhoto(id);
		model.addAttribute("photoVo", photoVo);
		return "viewPhoto";
	}

	@RequestMapping("managePhoto")
	public String managePhoto(HttpServletResponse response, Model model, Long id) {
		id = 1L;
		PhotoVo photoVo = viewPhoto(id);
		model.addAttribute("photoVo", photoVo);
		return "managePhoto";
	}

	// 如果没有1个图是主图，默认第1个为主图
	@RequestMapping("savePhoto")
	public void savePhoto(HttpServletResponse response, Long id, String photos) {
		id = 1L;
		List<Photo> list = JSONArray.parseArray(photos, Photo.class);
		savePhoto(id, list);
		super.jsonSucceed(response);
	}

	private PhotoVo viewPhoto(Long id) {
		PhotoVo photoVo = new PhotoVo();
		photoVo.setProjectId(id);
		List<Photo> photoList = photoDao.getPhotoListByProjectId(id);
		photoVo.setPhotoList(photoList);
		return photoVo;
	}

	public void savePhoto(Long id, List<Photo> list) {
		// 这个项目数据库中的图片
		List<Photo> dbList = photoDao.getPhotoListByProjectIdAllStatus(id);
		PhotoBean photoBean = handlePhoto(list, dbList);
		handleCover(id, photoBean);
		doAdd(id, photoBean.toAdd);
		doUpdate(id, photoBean.toUpdate);
		doDelete(id, photoBean.toDelete);
	}

	private void doAdd(Long id, List<Photo> list) {
		if (CollectionUtils.isNotEmpty(list)) {
			handleDefaultField(id, list);
			photoDao.batchAdd(list);
		}
	}

	private void doUpdate(Long id, List<Photo> list) {
		handleDefaultField(id, list);

		// 保存最新的
		if (CollectionUtils.isNotEmpty(list)) {
			for (Photo o : list) {
				photoDao.update(o);
			}
		}
	}

	private void handleDefaultField(Long id, List<Photo> list) {
		if (CollectionUtils.isNotEmpty(list)) {
			// 把项目id放进去
			for (Photo p : list) {
				p.setBizid(id);
				p.setType(1);
				p.setStatus(0);
			}
		}
	}

	private String handleCover(Long id, PhotoBean photoBean) {
		List<Photo> list = new ArrayList<Photo>();
		list.addAll(photoBean.toAdd);
		list.addAll(photoBean.toUpdate);

		String cover;
		if (CollectionUtils.isNotEmpty(list)) {
			// 如果不存在主图，选择第1个为主图.
			// 如果存在多个主图，选择最先发现的那个为主图,把其它的设置为“非主图”
			int size = list.size();
			Integer existIndex = -1;
			for (int index = 0; index < size; index++) {
				Photo photo = list.get(index);
				// 确保不会出现多个主图：如果已经找到了主图，把后面的都设置为“非主图”，防止前端验证失败，出现多个主图的情况
				if (existIndex != -1) {
					photo.setCover(0);
				}
				Integer c = photo.getCover();
				// 找到了主图
				if (c != null && c.equals(1)) {
					existIndex = index;
				}
			}
			// 不存在主图
			if (existIndex == -1) {
				list.get(0).setCover(1);
				existIndex = 0;
			}
			// 主图
			cover = list.get(existIndex).getUrl();

		} else {
			// 没有图片，把主图回写为空
			cover = "";
		}
		return cover;
	}

	private void doDelete(Long id, List<Photo> toDelete) {
		if (CollectionUtils.isNotEmpty(toDelete)) {
			for (Photo o : toDelete) {
				if (o == null || o.getId() == null) {
					logger.error("doDelete photo is null or id is null");
					continue;
				}
				photoDao.delete(o.getId());
				String url = o.getUrl();
				if (StringUtils.isEmpty(url) || url.length() < 7) {
					logger.error("doDelete photo,url is invalid~ null or  length < 6");
					continue;
				}
				if (StringUtils.isNoneBlank(url) && url.length() > 7) {
					// 不要前面的“group1/”
					String path = url.substring(7);
					try {
						logger.info("Fastdfs,Try to Delete File : " + path);
						// storageClientService.deleteFile("group1", path);
					} catch (Exception e) {
						logger.info("Delete file failed : " + e.getMessage());
						e.printStackTrace();
					}

				}
			}
		}

	}

	// 根据前端photo集合和数据库photo集合，得到需要更新和需要删除的photo集合，不存在需要增加的photo集合
	private PhotoBean handlePhoto(List<Photo> list, List<Photo> dbList) {
		PhotoBean bean = new PhotoBean();
		// 全部删除，什么图片都没有上传
		if (CollectionUtils.isEmpty(list)) {
			bean.toDelete = dbList;
		}
		// 全部增加，一般在第1次
		/*
		 * if (CollectionUtils.isEmpty(dbList)) { bean.toAdd = list; }
		 */
		// 都不为null
		if (list != null && dbList != null) {
			// 交集，肯定不为null，最多是empty,id相同就是共同存在
			List<Photo> commonList = ListUtils.retainAll(list, dbList);

			// 2者交集
			List<Photo> toUpdate = commonList;
			// 数据库中的临时图片，状态需要改为“正常”
			if (CollectionUtils.isNotEmpty(toUpdate)) {
				for (Photo p : toUpdate) {
					p.setStatus(0);
				}
			}

			// 在list，不在dbList中的
			List<Photo> toAdd = new ArrayList<Photo>();
			for (Photo p : list) {
				if (!dbList.contains(p)) {
					toAdd.add(p);
				}
			}
			// 在dbList，不在list中的
			List<Photo> toDelete = new ArrayList<Photo>();
			for (Photo p : dbList) {
				if (!list.contains(p)) {
					toDelete.add(p);
				}
			}
			bean.toAdd = toAdd;
			bean.toUpdate = toUpdate;
			bean.toDelete = toDelete;
		}
		return bean;

	}

}

class PhotoBean {
	// 将要删除的，通常是数据库中的
	public List<Photo> toDelete;
	// 将要更新的，都在数据库中，部分最新内容来源于web前端
	public List<Photo> toUpdate;
	// 将要增加的，由于上传图片的时候都已经插入了，这个时候可以忽略了，但是存在增加一条记录，但不上传图片的情况
	public List<Photo> toAdd;
}
